﻿using System;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using E4RPDevExpress10;
using E4RPTools;
using StationCommon;

namespace Station.Controls
{
    public partial class WorkSheet : UserControl
    {
        private Controller _controller;
        private bool _showingWorkOrder;
        private bool _updateWorkOrderItem;
        
        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.WorkSheetShow += delegate { UpdateControl(); };
                _controller.VehicleSaved += delegate { SetupVehicleData(); };
                _controller.MechanicSaved += delegate { SetupMechanicData(); };
            }
        }

        public void UpdateControl()
        {
            _showingWorkOrder = true;
            folhaObraDataSet.Clear();
            folhaObraDataSet.Merge(_controller.WorkOrder);
            gridControl.DataSource = null;
            gridControl.DataMember = "";
            gridControl.DataSource = folhaObraDataSet;
            gridControl.DataMember = folhaObraDataSet.ItemFolhaObra.TableName;
            SetupVehicleData();
            SetupProductData();
            SetupClientData();
            SetupMechanicData();
            colFactura.OptionsColumn.AllowEdit = false;
            bool enable = _controller.WorkOrder.FolhaObra[0].Id <= 0;
            vehicleRegistrationLookUpEdit.Enabled = enable && veiculoDataSet.Veiculo.Count > 0;
            receptionDateEdit.Enabled = enable;
            receptionTimeEdit.Enabled = enable;
            bool billed = _controller.WorkOrder.FolhaObra[0].Estado != WorkOrderState.Facturada.ToString();
            vehicleKmsTextEdit.Enabled = billed;
            deliveryDateEdit.Enabled = billed;
            deliveryTimeEdit.Enabled = billed;
            colReferencia.OptionsColumn.AllowEdit = billed;
            colQuantidade.OptionsColumn.AllowEdit = billed;
            colValorUnitario.OptionsColumn.AllowEdit = billed;
            colPercentagemDesconto.OptionsColumn.AllowEdit = billed;
            colPercentagemIva.OptionsColumn.AllowEdit = billed;
            colIdClienteFactura.OptionsColumn.AllowEdit = billed;
            colIdMecanico.OptionsColumn.AllowEdit = billed;
            gridControl.EmbeddedNavigator.Buttons.Append.Enabled = billed;
            gridControl.EmbeddedNavigator.Buttons.Remove.Enabled = billed;
            SetDataToControls();
            vehicleRegistrationLookUpEdit.ClosePopup();
            FormatGridColumns();
            _showingWorkOrder = false;
        }

        #endregion

        public void CloseEditors()
        {
            _controller.WorkOrder.FolhaObra[0].DataEntrega = (DateTime)deliveryDateEdit.EditValue;
            _controller.WorkOrder.FolhaObra[0].DataRecepcao = (DateTime)receptionDateEdit.EditValue;
            _controller.WorkOrder.FolhaObra[0].MatriculaVeiculo = vehicleRegistrationLookUpEdit.Text;
            _controller.WorkOrder.FolhaObra[0].NomeCliente = clientNameTextEdit.Text;
            _controller.WorkOrder.FolhaObra[0].KmsVeiculo = Convert.ToInt64(vehicleKmsTextEdit.EditValue);
            _controller.WorkOrder.FolhaObra[0].Estado = stateTextEdit.Text;
            _controller.WorkOrder.FolhaObra[0].Observacoes = remarksMemoEdit.Text;
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();            
        }

        public void ClearControlErrors()
        {
            dxErrorProvider.SetError(vehicleKmsTextEdit, "");
            dxErrorProvider.SetError(vehicleRegistrationLookUpEdit, "");
            dxErrorProvider.SetError(stateTextEdit, "");
            dxErrorProvider.SetError(receptionDateEdit, "");
            dxErrorProvider.SetError(deliveryDateEdit, "");
            dxErrorProvider.SetError(clientNameTextEdit, "");
            dxErrorProvider.SetError(vehicleModelTextEdit, "");
            dxErrorProvider.SetError(gridControl, "");            
        }

        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "ClienteNome":
                case "ClienteIdExterno":
                    return clientNameTextEdit;
                case "DataEntrega":
                    return deliveryDateEdit;
                case "DataRecepcao":
                    return receptionDateEdit;
                case "MatriculaVeiculo":
                    return vehicleRegistrationLookUpEdit;
                default:
                    return null;
            }
        }

        public void SetControlErrors(Result result)
        {
            foreach (Error error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        public void UpdateState()
        {
            stateTextEdit.Text = _controller.WorkOrder.FolhaObra[0].Estado;
        }                

        public WorkSheet()
        {
            InitializeComponent();
            vehicleRegistrationLookUpEdit.EditValueChanging += VehicleRegistrationLookUpEditEditValueChanging;
            gridView.InitNewRow += GridViewInitNewRow;
            gridView.CellValueChanging += GridViewCellValueChanging;
            productReferenceRepositoryItemLookUpEdit.EditValueChanging += ProductReferenceRepositoryItemLookUpEditEditValueChanging;
            clientRepositoryItemLookUpEdit.EditValueChanging += ClientRepositoryItemLookUpEditEditValueChanging;
            gridView.CellValueChanged += GridViewCellValueChanged;
            FormatGridColumns();
            gridControl.EmbeddedNavigator.ButtonClick += EmbeddedNavigatorButtonClick;
            gridView.ShowingEditor += GridViewShowingEditor;
            deliveryDateEdit.EditValueChanged += DeliveryDateEditEditValueChanged;
            deliveryTimeEdit.EditValueChanged += DeliveryTimeEditEditValueChanged;
            receptionDateEdit.EditValueChanged += ReceptionDateEditEditValueChanged;
            receptionTimeEdit.EditValueChanged += ReceptionTimeEditEditValueChanged;
        }

        void ReceptionTimeEditEditValueChanged(object sender, EventArgs e)
        {
            if (_showingWorkOrder) return;
            ReceptionDateTimeChanged();
            receptionDateEdit.EditValue = _controller.WorkOrder.FolhaObra[0].DataRecepcao;
        }

        void ReceptionDateEditEditValueChanged(object sender, EventArgs e)
        {
            if (_showingWorkOrder) return;
            ReceptionDateTimeChanged();
            receptionTimeEdit.EditValue = _controller.WorkOrder.FolhaObra[0].DataRecepcao;
        }

        void DeliveryTimeEditEditValueChanged(object sender, EventArgs e)
        {
            if (_showingWorkOrder) return;
            DeliveryDateTimeChanged();
            deliveryDateEdit.EditValue = _controller.WorkOrder.FolhaObra[0].DataEntrega;
        }

        void DeliveryDateEditEditValueChanged(object sender, EventArgs e)
        {
            if (_showingWorkOrder) return;
            DeliveryDateTimeChanged();
            deliveryTimeEdit.Time = _controller.WorkOrder.FolhaObra[0].DataEntrega;
        }        

        #region Private Methods

        private void DeliveryDateTimeChanged()
        {
            var date = ((DateTime)deliveryDateEdit.EditValue).Date;
            var hour = deliveryTimeEdit.Time.Hour;
            var minutes = deliveryTimeEdit.Time.Minute;
            _controller.WorkOrder.FolhaObra[0].DataEntrega = date.Date;
            _controller.WorkOrder.FolhaObra[0].DataEntrega = _controller.WorkOrder.FolhaObra[0].DataEntrega.AddHours(hour);
            _controller.WorkOrder.FolhaObra[0].DataEntrega = _controller.WorkOrder.FolhaObra[0].DataEntrega.AddMinutes(minutes);
        }

        private void ReceptionDateTimeChanged()
        {
            var date = ((DateTime)receptionDateEdit.EditValue).Date;
            var hour = receptionTimeEdit.Time.Hour;
            var minutes = receptionTimeEdit.Time.Minute;
            _controller.WorkOrder.FolhaObra[0].DataRecepcao = date.Date;
            _controller.WorkOrder.FolhaObra[0].DataRecepcao = _controller.WorkOrder.FolhaObra[0].DataRecepcao.AddHours(hour);
            _controller.WorkOrder.FolhaObra[0].DataRecepcao = _controller.WorkOrder.FolhaObra[0].DataRecepcao.AddMinutes(minutes);
        }

        private void FormatGridColumns()
        {
            DevExpressHelper.SetColumnAsCurrency(colValorUnitario);
            DevExpressHelper.SetColumnAsCurrency(colValorBase);
            DevExpressHelper.SetColumnAsCurrency(colValorDesconto);
            DevExpressHelper.SetColumnAsNumeric(colPercentagemDesconto);
            DevExpressHelper.SetColumnAsCurrency(colValorSemIva);
            colValorSemIva.OptionsColumn.AllowEdit = false;
            DevExpressHelper.SetColumnAsNumeric(colPercentagemIva);
            DevExpressHelper.SetColumnAsCurrency(colValorComIva);
        }
        
        private void SetupVehicleData()
        {
            veiculoDataSet.Clear();
            veiculoDataSet.Merge(_controller.Vehicles());
            vehicleRegistrationLookUpEdit.Properties.DataSource = veiculoDataSet.Veiculo;
            vehicleRegistrationLookUpEdit.Properties.DisplayMember = veiculoDataSet.Veiculo.MatriculaColumn.ToString();
            vehicleRegistrationLookUpEdit.Properties.ValueMember = veiculoDataSet.Veiculo.MatriculaColumn.ToString();
            vehicleRegistrationLookUpEdit.Properties.Columns.Clear();
            vehicleRegistrationLookUpEdit.Properties.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Matricula", "Matricula", 70, FormatType.None, "", true, HorzAlignment.Near)});
            vehicleRegistrationLookUpEdit.Properties.PopupWidth = vehicleRegistrationLookUpEdit.Width;
        }
         
        private void SetupProductData()
        {
            produtoDataSet.Clear();
            produtoDataSet.Merge(_controller.Products());
            productReferenceRepositoryItemLookUpEdit.DataSource = produtoDataSet.Produto;
            productReferenceRepositoryItemLookUpEdit.DisplayMember = produtoDataSet.Produto.ReferenciaColumn.ToString();
            productReferenceRepositoryItemLookUpEdit.ValueMember = produtoDataSet.Produto.ReferenciaColumn.ToString();
            productReferenceRepositoryItemLookUpEdit.Columns.Clear();
            productReferenceRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Referencia", "Referencia", 70, FormatType.None, "", true, HorzAlignment.Near),
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Descricao", "Descricao", 70, FormatType.None, "", true, HorzAlignment.Near)});
         }

        private void SetupClientData()
        {
            clienteDataSet.Clear();
            clienteDataSet.Merge(_controller.Clients());
            clientRepositoryItemLookUpEdit.DataSource = clienteDataSet.Cliente;
            clientRepositoryItemLookUpEdit.DisplayMember = clienteDataSet.Cliente.NomeColumn.ToString();
            clientRepositoryItemLookUpEdit.ValueMember = clienteDataSet.Cliente.IdColumn.ToString();
            clientRepositoryItemLookUpEdit.Columns.Clear();
            clientRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetupMechanicData()
        {
            mecanicoDataSet.Clear();
            mecanicoDataSet.Mecanico.AddMecanicoRow(Convert.ToInt64(null) , "");
            mecanicoDataSet.Merge(_controller.Mechanics());
            mechanicRepositoryItemLookUpEdit.DataSource = mecanicoDataSet.Mecanico;
            mechanicRepositoryItemLookUpEdit.DisplayMember = mecanicoDataSet.Mecanico.NomeColumn.ToString();
            mechanicRepositoryItemLookUpEdit.ValueMember = mecanicoDataSet.Mecanico.IdColumn.ToString();
            mechanicRepositoryItemLookUpEdit.Columns.Clear();
            mechanicRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetDataToControls()
        {
            nameTextEdit.Text = _controller.WorkOrder.FolhaObra[0].Nome;
            deliveryDateEdit.EditValue = _controller.WorkOrder.FolhaObra[0].DataEntrega;
            deliveryTimeEdit.Time = _controller.WorkOrder.FolhaObra[0].DataEntrega;
            receptionDateEdit.EditValue = _controller.WorkOrder.FolhaObra[0].DataRecepcao;
            receptionTimeEdit.EditValue = _controller.WorkOrder.FolhaObra[0].DataRecepcao;            
            vehicleRegistrationLookUpEdit.Text = _controller.WorkOrder.FolhaObra[0].MatriculaVeiculo;
            clientNameTextEdit.Text = _controller.WorkOrder.FolhaObra[0].NomeCliente;
            vehicleKmsTextEdit.EditValue = _controller.WorkOrder.FolhaObra[0].KmsVeiculo;
            stateTextEdit.Text = _controller.WorkOrder.FolhaObra[0].Estado;
            remarksMemoEdit.Text = _controller.WorkOrder.FolhaObra[0].IsObservacoesNull() ? "" : _controller.WorkOrder.FolhaObra[0].Observacoes;
        }

        private ClienteDataSet.ClienteRow GetClient(string id)
        {
            foreach (ClienteDataSet.ClienteRow client in clienteDataSet.Cliente)
                if (client.Id == id)
                    return client;
            return null;
        }

        private ProdutoDataSet.ProdutoRow GetProduct(string reference)
        {
            foreach (ProdutoDataSet.ProdutoRow product in produtoDataSet.Produto)
                if (product.Referencia == reference)
                    return product;
            return null;
        }

        #endregion

        void VehicleRegistrationLookUpEditEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (_showingWorkOrder)
                return;
            var vehicle = new VeiculoDataSet();
            vehicle.Merge(_controller.GetVehicle(e.NewValue.ToString()));
            if (vehicle.Veiculo.Count == 0)
            {
                _controller.WorkOrder.FolhaObra[0].MatriculaVeiculo = "";
                _controller.WorkOrder.FolhaObra[0].NomeCliente = "";
                _controller.WorkOrder.FolhaObra[0].IdCliente = "";
                _controller.WorkOrder.FolhaObra[0].KmsVeiculo = 0;
            }
            else
            {
                _controller.WorkOrder.FolhaObra[0].MatriculaVeiculo = e.NewValue.ToString();
                _controller.WorkOrder.FolhaObra[0].NomeCliente = vehicle.Veiculo[0].NomeCliente;
                _controller.WorkOrder.FolhaObra[0].IdCliente = vehicle.Veiculo[0].IdCliente;
                _controller.WorkOrder.FolhaObra[0].KmsVeiculo = vehicle.Veiculo[0].IsKmsNull() ? 0 : vehicle.Veiculo[0].Kms;
            }
            clientNameTextEdit.Text = vehicle.Veiculo[0].NomeCliente;
            vehicleKmsTextEdit.Text = _controller.WorkOrder.FolhaObra[0].KmsVeiculo.ToString();
            vehicleModelTextEdit.Text = vehicle.Veiculo[0].Modelo;
            //_controller.UpdateClientWorkSheetItems(vehicle.Veiculo[0].IdCliente);
        }

        void ProductReferenceRepositoryItemLookUpEditEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (_showingWorkOrder)
                return;
            _updateWorkOrderItem = true;
            int rowHandle = gridView.FocusedRowHandle;
            ProdutoDataSet.ProdutoRow product = GetProduct(e.NewValue.ToString());
            decimal quantity = Convert.ToDecimal(gridView.GetRowCellValue(rowHandle, colQuantidade));
            decimal baseValue = Math.Round(quantity * product.Valor, 2);
            decimal discountPercentage = Convert.ToDecimal(gridView.GetRowCellValue(rowHandle, colPercentagemDesconto));
            decimal discountValue = Math.Round(baseValue * discountPercentage / 100, 2);
            decimal valueWithoutVat = baseValue - discountValue;
            gridView.SetRowCellValue(rowHandle, colPercentagemIva, product.PercentagemIva);
            decimal vatPercentage = Convert.ToDecimal(gridView.GetRowCellValue(rowHandle, colPercentagemIva));
            decimal valueVat = Math.Round(valueWithoutVat * vatPercentage / 100, 2);
            decimal valueWithVat = valueWithoutVat + valueVat;
            gridView.SetRowCellValue(rowHandle, colDescricao, product.Descricao);
            gridView.SetRowCellValue(rowHandle, colValorUnitario, product.Valor);
            gridView.SetRowCellValue(rowHandle, colValorBase, baseValue);
            gridView.SetRowCellValue(rowHandle, colValorDesconto, discountValue);
            gridView.SetRowCellValue(rowHandle, colValorSemIva, valueWithoutVat);
            gridView.SetRowCellValue(rowHandle, colValorIva, valueVat);
            gridView.SetRowCellValue(rowHandle, colValorComIva, valueWithVat);            
        }
        
        void GridViewCellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (_showingWorkOrder)
                return;
            _updateWorkOrderItem = true;
            decimal quantity, unitaryValue, baseValue, discountPercentage, discountValue, valueWithoutVat, vatPercentage, valueVat, valueWithVat;
            switch (e.Column.Name)
            {
                case "colQuantidade":
                    quantity = e.Value.ToString() == "" ? 0 : Convert.ToDecimal(e.Value);
                    unitaryValue = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colValorUnitario));
                    baseValue = Math.Round(quantity * unitaryValue, 2);
                    discountPercentage = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colPercentagemDesconto));
                    discountValue = Math.Round(baseValue*discountPercentage/100, 2);
                    valueWithoutVat = baseValue - discountValue;
                    vatPercentage= Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colPercentagemIva));
                    valueVat = Math.Round(valueWithoutVat * vatPercentage / 100, 2);
                    valueWithVat = Math.Round(valueWithoutVat + (valueWithoutVat * vatPercentage / 100), 2);
                    gridView.SetRowCellValue(e.RowHandle, colValorBase, baseValue);
                    gridView.SetRowCellValue(e.RowHandle, colValorDesconto, discountValue);
                    gridView.SetRowCellValue(e.RowHandle, colValorSemIva, valueWithoutVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorIva, valueVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorComIva, valueWithVat);
                    break;
                case "colValorUnitario":
                    unitaryValue = e.Value.ToString() == "" ? 0 : Convert.ToDecimal(e.Value);
                    quantity = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colQuantidade));
                    baseValue = Math.Round(quantity * unitaryValue, 2);
                    discountPercentage = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colPercentagemDesconto));
                    discountValue = Math.Round(baseValue * discountPercentage / 100, 2);
                    valueWithoutVat = baseValue - discountValue;
                    vatPercentage = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colPercentagemIva));
                    valueVat = Math.Round(valueWithoutVat * vatPercentage / 100, 2);
                    valueWithVat = Math.Round(valueWithoutVat + (valueWithoutVat * vatPercentage / 100), 2);
                    gridView.SetRowCellValue(e.RowHandle, colValorBase, baseValue);
                    gridView.SetRowCellValue(e.RowHandle, colValorDesconto, discountValue);
                    gridView.SetRowCellValue(e.RowHandle, colValorSemIva, valueWithoutVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorIva, valueVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorComIva, valueWithVat);
                    break;
                case "colPercentagemDesconto":
                    discountPercentage = e.Value.ToString() == "" ? 0 : Convert.ToDecimal(e.Value);
                    baseValue = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colValorBase));
                    discountValue = Math.Round(baseValue * discountPercentage / 100, 2);
                    valueWithoutVat = baseValue - discountValue;
                    vatPercentage = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colPercentagemIva));
                    valueVat = Math.Round(valueWithoutVat * vatPercentage / 100, 2);
                    valueWithVat = Math.Round(valueWithoutVat + (valueWithoutVat * vatPercentage / 100), 2);
                    gridView.SetRowCellValue(e.RowHandle, colValorDesconto, discountValue);
                    gridView.SetRowCellValue(e.RowHandle, colValorSemIva, valueWithoutVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorIva, valueVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorComIva, valueWithVat);
                    break;
                case "colPercentagemIva":
                    vatPercentage = e.Value.ToString() == "" ? 0 : Convert.ToDecimal(e.Value);
                    valueWithoutVat = Convert.ToDecimal(gridView.GetRowCellValue(e.RowHandle, colValorSemIva));
                    valueVat = Math.Round(valueWithoutVat * vatPercentage / 100, 2);
                    valueWithVat = Math.Round(valueWithoutVat + (valueWithoutVat * vatPercentage / 100), 2);
                    gridView.SetRowCellValue(e.RowHandle, colValorIva, valueVat);
                    gridView.SetRowCellValue(e.RowHandle, colValorComIva, valueWithVat);
                    break;
            }
        }

        void GridViewInitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _updateWorkOrderItem = false;
            var workSheetItem = _controller.AddWorkOrderItem();
            gridView.SetRowCellValue(e.RowHandle, colIdItem, workSheetItem.IdItem);
            gridView.SetRowCellValue(e.RowHandle, colId, workSheetItem.Id);
            gridView.SetRowCellValue(e.RowHandle, colQuantidade, 1);
            gridView.SetRowCellValue(e.RowHandle, colValorUnitario, 0);
            gridView.SetRowCellValue(e.RowHandle, colValorBase, 0);
            gridView.SetRowCellValue(e.RowHandle, colPercentagemDesconto, 0);
            gridView.SetRowCellValue(e.RowHandle, colValorDesconto, 0);
            gridView.SetRowCellValue(e.RowHandle, colValorSemIva, 0);
            gridView.SetRowCellValue(e.RowHandle, colPercentagemIva, 0);
            gridView.SetRowCellValue(e.RowHandle, colValorIva, 0);
            gridView.SetRowCellValue(e.RowHandle, colValorComIva, 0);
            gridView.SetRowCellValue(e.RowHandle, colFacturar, workSheetItem.Facturar);
            gridView.SetRowCellValue(e.RowHandle, colEstado, workSheetItem.Estado);
            if (_controller.WorkOrder.FolhaObra[0].NomeCliente == "") return;
            gridView.SetRowCellValue(e.RowHandle, colIdClienteFactura, workSheetItem.IdClienteFactura);
            gridView.SetRowCellValue(e.RowHandle, colNomeClienteFactura, workSheetItem.NomeClienteFactura);
        }

        void GridViewCellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (_showingWorkOrder || !_updateWorkOrderItem)
                return;
            var workSheetItem = (FolhaObraDataSet.ItemFolhaObraRow)gridView.GetDataRow(e.RowHandle);
            _controller.UpdateWorkSheetItem(workSheetItem);
        }

        void ClientRepositoryItemLookUpEditEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (_showingWorkOrder)
                return;
            _updateWorkOrderItem = true;
            var rowHandle = gridView.FocusedRowHandle;
            var client = GetClient(e.NewValue.ToString());
            gridView.SetRowCellValue(rowHandle, colNomeClienteFactura, client.Nome);
            gridView.SetRowCellValue(rowHandle, colIdClienteFactura, client.Id);            
            e.Cancel = false;
        }

        void EmbeddedNavigatorButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (e.Button.ButtonType != NavigatorButtonType.Remove) return;
            var workSheetItem = (FolhaObraDataSet.ItemFolhaObraRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            _controller.RemoveWorkSheetItem(workSheetItem);
            e.Handled = false;
        }

        void GridViewShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = gridView.GetRowCellValue(gridView.FocusedRowHandle, colEstado).ToString() != WorkOrderItemState.Facturar.ToString();
        }

    }
}
